package com.uduemc.biso.node.web.component;

import java.io.File;

import org.jodconverter.core.office.OfficeException;
import org.jodconverter.core.office.OfficeManager;
import org.jodconverter.local.JodConverter;
import org.jodconverter.local.office.LocalOfficeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.uduemc.biso.node.core.property.GlobalProperties;

@Configuration
public class LibreOfficeConverter {

	private static Logger logger = LoggerFactory.getLogger(LibreOfficeConverter.class);

	@Autowired
	private GlobalProperties globalProperties;

	@Bean(initMethod = "start", destroyMethod = "stop")
	public OfficeManager officeManager() {
		return this.createOfficeManager();
	}

	private OfficeManager createOfficeManager() {
		LocalOfficeManager.Builder builder = LocalOfficeManager.builder();

		builder.install();
		builder.officeHome(globalProperties.getLibreOffice().getOfficeHome());
		builder.portNumbers(globalProperties.getLibreOffice().getPortNumbers());
		return builder.build();
	}

	public static void convertFile(String input, String output) throws RuntimeException {
		File inputFile = new File(input);
		File outputFile = new File(output);

		try {
			logger.info("start convert:" + input + "  to:" + output);
			JodConverter.convert(inputFile).to(outputFile).execute();
			logger.info("end convert");
		} catch (OfficeException e) {
			throw new RuntimeException(e);
		}
	}
}
